declare @MainGroup nvarchar(3)
declare @MinorGroup nvarchar(3)
declare @MajorGroup nvarchar(3)
declare @ItemCode nvarchar(20)

set @MainGroup=101-- $[OITM.ItmsGrpCod]
set @MajorGroup=100--$[OITM.U_MajorGroup]
set @MinorGroup=100--$[OITM.U_MinorGroup]

declare @LastItemCode nvarchar(20)

select top 1 @LastItemCode= ItemCode from OITM T0
where ItmsGrpCod=@MainGroup
and U_MinorGroup=@MINORGROUP
and U_MajorGroup=@MAJORGROUP
order by ItemCode desc
print @LastItemCode
if @LastItemCode is null
begin
	set @ItemCode=@MainGroup+@MajorGroup+@MinorGroup+'0001'
end
else
begin
	declare @MaxCode int
	set @MaxCode=CONVERT(int,RIGHT(@LastItemCode,4)) + 1
	
	set @ItemCode=@MainGroup+@MajorGroup+@MinorGroup+ RIGHT('0000'+CONVERT(nvarchar(4),@MaxCode),4)
end

select @ItemCode

